import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaSwitch } from 'comsMobx';
import { WeaSearchGroup, WeaRightMenu, WeaFormItem, WeaLocaleProvider, WeaErrorPage, WeaTools, WeaDialog, WeaTransfer } from 'ecCom'
import { Row, Col, Button } from 'antd';
import './index.less';
import { toJS } from 'mobx';
import cloneDeep from 'lodash/cloneDeep';
const getLabel = WeaLocaleProvider.getLabel;

@observer
class MobileCenterContent extends React.Component {

    constructor(props) {
        super(props);
        this.getSearchs;

        this.state = {
            orderColDatas_state: [],
            selectedOrder_state: [],
            needSyn: true
        }
    }

    render() {
        const { isShow, setDialogShow, wfMobileSettingStore } = this.props;
        const { showDialog, wfContentLoading } = wfMobileSettingStore;
        return (
            <div>
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@3yu19n`}
                    onCancel={() => {
                        this.resetState();
                        setDialogShow('contentSetting', false)
                    }}
                    visible={isShow}
                    style={{
                        width: "650px",
                        height: "400px"
                    }}
                    hasScroll={true}
                    buttons={this.getButtons()}
                    icon={'icon-coms-workflow'}
                    iconBgcolor='#0079DE'
                    title={getLabel(504014, '内容设置')}
                    moreBtn={this.getMoreBtns()}

                >
                    {showDialog.orderCol === true && this.getOrderColDialog()}
                    {!wfContentLoading && <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@y58jpw`} {...this.getMoreBtns()} >
                        {
                            <div>  {this.getSearchs()}
                            </div>
                        }
                    </WeaRightMenu>}
                </WeaDialog>
            </div>
        );
    }

    //流程中心应用--内容设置--排序字段穿梭框
    getOrderColDialog() {
        const { wfMobileSettingStore } = this.props;
        const { showDialog, setDialogShow, selectedOrders = [], orderColDatas = [] } = wfMobileSettingStore;
        const { orderColDatas_state, selectedOrder_state, needSyn } = this.state;
        if (needSyn && toJS(orderColDatas_state) != toJS(orderColDatas)) {
            this.setState({ orderColDatas_state: cloneDeep(orderColDatas) });
            this.setState({ selectedOrder_state: selectedOrders });
            this.setState({ needSyn: false });
        }
        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@rffkck`}
                title={getLabel(386541, '排序字段设置')}
                icon={'icon-coms-workflow'}
                iconBgcolor="#0079DE"
                onCancel={() => {
                    this.resetState();
                    setDialogShow('orderCol', false);
                }}
                visible={showDialog.orderCol}
                style={{ width: 680, height: 360 }}
                buttons={this.getOrderColButtons()}
            >
                <WeaTransfer ecId={`${this && this.props && this.props.ecId || ''}_WeaTransfer@m58zib`}
                    data={orderColDatas_state}
                    height={354}
                    renderItem={this.renderItem}
                    renderRight={this.renderSortItem}
                    selectedKeys={selectedOrder_state}
                    onChange={(keys, datas) => {
                        this.setState({ selectedOrder_state: keys });
                    }}
                    ref='orderCol'
                />
            </WeaDialog>
        )
    }

    //流程中心应用--内容设置--condition渲染
    getSearchs = () => {
        const { wfMobileSettingStore } = this.props;
        const { contentSettingForm, contentSettingFields = [], viewtypeFields = [], selectedOrders = [], orderColDatasMap = {}, setDialogShow } = wfMobileSettingStore;
        let group = [];
        let items = [];
        if (contentSettingForm && contentSettingForm.isFormInit) {
            const formParams = contentSettingForm && contentSettingForm.getFormParams();
            const showWf = formParams && (formParams.sourcetype == 1 || formParams.sourcetype == 2);
            const showWfType = formParams && (formParams.sourcetype == 3 || formParams.sourcetype == 4);
            const viewtype = formParams && formParams.viewtype;
            let needcontinue = false;
            contentSettingFields.map(field => {
                const domkey = field.domkey[0];
                if (domkey === "viewtype") {//查看类型以及查看类型辅助项condition渲染
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@9sc8wu@${domkey}`}
                            label={`${field.label}`}
                            labelCol={{ span: `${field.labelcol}` }}
                            wrapperCol={{ span: `${field.fieldcol}` }}
                            error={contentSettingForm.getError(field)}
                            tipPosition="bottom"
                        >
                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@s4v3m1@${domkey}`} fieldConfig={field} form={contentSettingForm} formParams={formParams} />
                            {viewtypeFields && viewtypeFields.map((viewItem, index) => {//填充辅助设置项condition
                                const uniqueKey = `${domkey}_${index}`;
                                if (needcontinue === true) {
                                    needcontinue = false;
                                    return;
                                }
                                let nextItem = null;
                                if (viewtypeFields.length > (index + 1)) {
                                    nextItem = viewtypeFields[index + 1];
                                }
                                if (viewItem.otherParams && viewItem.otherParams.key == viewtype && nextItem && nextItem.otherParams && nextItem.otherParams.key == viewtype) {
                                    needcontinue = true;//辅助设置项超过一个，则每两个选项占一行
                                    return (<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@sx6550@${uniqueKey}`}>
                                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ot0rm8@${uniqueKey}`} span={12}><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ycgbkb@${uniqueKey}`} fieldConfig={{ ...viewItem, content: viewItem.label }} form={contentSettingForm} /></Col>
                                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@pc3a07@${uniqueKey}`} span={12}><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@guythe@${uniqueKey}`} fieldConfig={{ ...nextItem, content: nextItem.label }} form={contentSettingForm} /></Col>
                                    </Row>)
                                } else if (viewItem.otherParams && viewItem.otherParams.key == viewtype && viewItem.otherParams.type == "selected") {//下拉框需要加padding样式
                                    return (
                                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zelknz@${uniqueKey}`} style={{ paddingTop: "8px" }}>
                                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rjilvr@${uniqueKey}`} span={9}><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@wd8sr3@${uniqueKey}`} fieldConfig={{ ...viewItem, content: viewItem.label }} form={contentSettingForm} /></Col>
                                        </Row>)
                                } else if (viewItem.otherParams && viewItem.otherParams.key == viewtype) {//单条件独占一行
                                    return (
                                        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@fc2cih@${uniqueKey}`} style={{ textOverflow: "ellipsis" }}>
                                            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2p6frb@${uniqueKey}`} span={24}><WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0oy6sx@${uniqueKey}`} fieldConfig={{ ...viewItem, content: viewItem.label }} form={contentSettingForm} /></Col>
                                        </Row>)
                                }
                            })}
                        </WeaFormItem>),
                        col: 1
                    });
                } else if (domkey === "ordercol") {//排序字段设置
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@xerj4h@${domkey}`}
                            label={`${field.label}`}
                            labelCol={{ span: `${field.labelcol}` }}
                            wrapperCol={{ span: `${field.fieldcol}` }}
                            error={contentSettingForm.getError(field)}
                            tipPosition="bottom"
                        >
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6xgxtb@${domkey}`} type='flex' align='middle' >
                                <span style={{ marginRight: '5px', marginTop: '8px' }}><i className="icon-coms-Flow-setting icon" style={{ cursor: 'pointer', fontSize: '14px' }} onClick={() => setDialogShow('orderCol', true)} /></span>
                                {
                                    selectedOrders.length > 0 && selectedOrders.map(v => {
                                        if (orderColDatasMap[v]) {
                                            const { fieldshowname = '', ordertype = '0' } = orderColDatasMap[v];
                                            const txt = '-' + (ordertype === '0' ? getLabel(384984, "降序") : getLabel(384985, "升序"));
                                            //const color = ordertype === '1' ? '#FF6666' : '#00CC99';
                                            return <span style={{ marginRight: '5px', marginTop: '5px' }}>{fieldshowname}<span>{txt}</span></span>
                                        }
                                    })
                                }
                            </Row>
                        </WeaFormItem>),
                        col: 1
                    });
                } else if ((domkey === "workflowids" && showWf) || (domkey === "workflowtypes" && showWfType) || ((!field.otherParams || !field.otherParams.key || field.otherParams.key == '') && domkey != "workflowids" && domkey != "workflowtypes")) {
                    items.push({
                        com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@0z7otg@${domkey}`}
                            label={`${field.label}`}
                            labelCol={{ span: `${field.labelcol}` }}
                            wrapperCol={{ span: `${field.fieldcol}` }}
                            error={contentSettingForm.getError(field)}
                            tipPosition="bottom"
                        >
                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@mf0cnk@${domkey}`} fieldConfig={field} form={contentSettingForm} formParams={formParams} />
                        </WeaFormItem>),
                        col: 1
                    });
                }
            });
        }

        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wgqp2i@group1`} needTigger={false} showGroup={true} items={items} />);
        return group;
    }

    //流程中心应用--内容设置--排序字段穿梭框--左侧数据样式
    renderItem = (item) => {
        return (
            <div className="wfcenter-orderCol-render-item">
                <p>{item.fieldshowname}</p>
            </div>
        )
    }

    //流程中心应用--内容设置--排序字段穿梭框--右侧数据带排序样式
    renderSortItem = (item) => {
        const { fieldshowname, ordertype = 'asc' } = item;
        return (
            <div className="wfcenter-orderCol-render-item" title={item.fieldshowname}>
                <div className="item-info-right">
                    <p>{item.fieldshowname}</p>
                </div>
                <div className="item-info-order">
                    <a onClick={e => { this.changeOrder(e, item, ordertype === "0" ? "1" : "0") }} onDoubleClick={e => e.stopPropagation()}>{ordertype === '0' ? getLabel(384984, '降序') : getLabel(384985, '升序')}</a>
                </div>
            </div>
        )
    }

    //流程中心应用--内容设置--排序字段穿梭框--改变排序字段升序、降序设置
    changeOrder = (e, item = {}, v) => {
        e.preventDefault && e.preventDefault();
        e.stopPropagation && e.stopPropagation();
        const { orderColDatas_state } = this.state;
        let newData = [...orderColDatas_state];
        for (let i = 0; i < newData.length; i++) {
            if (newData[i].id == item.id) {
                newData[i].ordertype = v;
                break;
            }
        }
        this.setState({ orderColDatas_state: newData });
    }

    //流程中心应用--内容设置更多button
    getMoreBtns() {
        let btns = [];
        btns.push({
            key: '0',
            icon: <i className='icon-coms-Preservation' />,
            content: getLabel(86, '保存'),
            onClick: key => this.saveData(),
        });
        return { datas: btns };
    }

    //流程中心应用--内容设置button
    getButtons() {
        let btn = [];
        btn.push(
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@gprx0r@save`} type="primary" onClick={this.saveData} >{getLabel(86, '保存')}</Button>)
        )
        return btn;
    }

    //流程中心应用--内容设置--排序字段穿梭框--底部按钮
    getOrderColButtons() {
        const { wfMobileSettingStore } = this.props;
        const { orderColDatas_state, selectedOrder_state } = this.state;
        const { setDialogShow, setSelectedOrders, setOrderColDatas } = wfMobileSettingStore;
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@yx7ste@confirm`} disabled={false} type="primary" onClick={() => {
            setOrderColDatas(orderColDatas_state, true);
            setSelectedOrders(selectedOrder_state, true);
            setDialogShow('orderCol', false);
        }}>{getLabel(826, '确定')}</Button>);
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ydxv86@cancel`} disabled={false} onClick={() => {
            this.setState({ needSyn: true });
            setDialogShow('orderCol', false);
        }}>{getLabel(201, '取消')}</Button>);
        return buttons;
    }

    //流程中心应用--内容设置保存方法
    saveData = () => {
        const { wfMobileSettingStore } = this.props;
        const { doSaveMobilecenterConfig, currentTabid } = wfMobileSettingStore;
        this.resetState();
        doSaveMobilecenterConfig({ type: "contentSetting", tabid: currentTabid });
    }

    //重置state属性
    resetState = () =>{
        this.setState({orderColDatas_state:[],selectedOrder_state:[],needSyn:true});
    }

}

export default WeaTools.tryCatch(React,
    props => < WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@x5bzc6`} msg={
        props.error ? props.error : '对不起，该页面异常，请联系管理员！'
    }
    />, {
    error: ""
}
)(MobileCenterContent);